package com.wantup.springboot.boot.servlet_file_listener;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2018/11/13 15:41
 * https://blog.csdn.net/amanicspater/article/details/74267444
 */
public class PersonFilter implements Filter {
    String NO_LOGIN = "您还未登录";
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/login", "/logout", "/register","/index")));
    String[] includeUrls = new String[]{"/login", "/logout", "/register"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("PersonFilter ... init ...");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
//        System.out.println("PersonFilter ... doFilter ...");
//        HttpServletRequest request = (HttpServletRequest) req;
//        HttpServletResponse response = (HttpServletResponse) res;
//
//        HttpSession session = request.getSession(false);
//        String uri = request.getRequestURI();
////
        filterChain.doFilter(req, res);





//        // 不过滤的uri
//        String[] notFilter = new String[] { "index"};
//        // 请求的uri
//        String uri = request.getRequestURI();
//        // uri中包含pages时才进行过滤
//        if (uri.indexOf("article") != -1) {
//            // 是否过滤
//            boolean doFilter = true;
//            for (String s : notFilter) {
//                if (uri.indexOf(s) != -1) {
//                    // 如果uri中包含不过滤的uri，则不进行过滤
//                    doFilter = false;
//                    break;
//                }
//            }
//            if (doFilter) {
//                // 执行过滤
//                // 从session中获取登录者实体
//                Object obj = request.getSession().getAttribute("user");
//                if (null == obj) {
//                    // 如果session中不存在登录者实体，则弹出框提示重新登录
//                    // 设置request和response的字符集，防止乱码
//                    request.setCharacterEncoding("UTF-8");
//                    response.setCharacterEncoding("UTF-8");
//                    PrintWriter out = response.getWriter();
//                    String loginPage = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
//                    StringBuilder builder = new StringBuilder();
//                    builder.append("<script charset=\"UTF-8\" language=\"javascript\" type=\"text/javascript\">");
//                    builder.append("alert('网页过期，请重新登录！');");
//                    builder.append("window.top.location.href='");
//                    builder.append(loginPage);
//                    builder.append("';");
//                    builder.append("</script>");
//                    out.print(builder.toString());
//                } else {
//                    // 如果session中存在登录者实体，则继续
//                    filterChain.doFilter(request, response);
//                }
//            } else {
//                // 如果不执行过滤，则继续
//                filterChain.doFilter(request, response);
//            }
//        } else {
//            // 如果uri中不包含background，则继续
//            filterChain.doFilter(request, response);
//        }











//        System.out.println("filter url:" + uri); //是否需要过滤
//        boolean needFilter = isNeedFilter(uri);
//        if (!needFilter) {
//            //不需要过滤直接传给下一个过滤器
//            filterChain.doFilter(req, res);
//        } else {
//            //需要过滤器 // session中包含user对象,则是登录状态
//            if (session != null && session.getAttribute("user") != null) {
//                // System.out.println("user:"+session.getAttribute("user"));
//                filterChain.doFilter(request, response);
//            } else {
//                String requestType = request.getHeader("X-Requested-With");
//                //判断是否是ajax请求
//                if (requestType != null && "XMLHttpRequest".equals(requestType)) {
//                    response.getWriter().write(this.NO_LOGIN);
//                } else {
//                    //重定向到登录页(需要在static文件夹下建立此html文件)
//                    response.sendRedirect(request.getContextPath() + "/toIndex");
//                }
//                return;
//            }
//        }

//        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
//        System.out.println("请求过来的路径  : " + path);
//        boolean allowedPath = ALLOWED_PATHS.contains(path);
//
//        if (!allowedPath) {
//            System.out.println("这里是不需要处理的url进入的方法");
//            chain.doFilter(req, res);
//        } else {
//            System.out.println("这里是需要处理的url进入的方法");
//            //chain.doFilter(req, res);
//            if (session != null && session.getAttribute("user") != null) {
//                chain.doFilter(req, res);
//            } else {
//                String requestType = request.getHeader("X-Requested-With"); //判断是否是ajax请求
//
//                if (requestType != null && "XMLHttpRequest".equals(requestType)) {
////                    response.getWriter().write(this.NO_LOGIN);
//                    response.sendRedirect(request.getContextPath() + "/index");
//
//                } else {
//                    //重定向到登录页(需要在static文件夹下建立此html文件)
//                    response.sendRedirect(request.getContextPath() + "/index");
//                }
//                return;
//            }
//
//
//        }


//        String uri = req.getRequestURI();
//        System.out.println("--------------------->过滤器：请求地址"+uri);
//        if (!uri.contains("login")){
//            res.sendRedirect("/index");
////            servletRequest.getRequestDispatcher("/index").forward(servletRequest, servletResponse);
//        }else{
//            filterChain.doFilter(servletRequest, servletResponse);
//        }

    }


    /**
     * @param uri
     * @Author: xxxxx
     * @Description: 是否需要过滤
     * @Date: 2018-03-12 13:20:54
     */
    public boolean isNeedFilter(String uri) {
        for (String includeUrl : includeUrls) {
            if (includeUrl.equals(uri)) {
                return false;
            }
        }
        return true;
    }


    @Override
    public void destroy() {
        System.out.println("PersonFilter ... destroy ...");
    }


}
